#!/bin/bash

PASSWORD=123456
HOST=127.0.0.1
PORT=3306
BRANCH=

while getopts "H:hp:P:b:" opt; do
    case "$opt" in
    H) HOST=$OPTARG
	    ;; 
    h)
    	printf "Usage:\n\tsetup-persist-db.sh [-H <DB host>] [-P <DB port>] [-p <DB root password>] [-b <branch name>]\n"
        exit 0
        ;;
    p)  PASSWORD=$OPTARG
        ;;
    P)  PORT=$OPTARG
        ;;
    b)  BRANCH=$OPTARG
        ;;
    esac
done

if [ ! -f ../db/app-database.sql ]; then
    printf "Error: Unable to find database.sql\n"
    exit 2
fi

#if [ ! -f ../db/ehcore-platform-schema.sql ]; then
#    printf "Error: Unable to find ehcore-platform-schema.sql\n"
#    exit 3
#fi

handle_error() {
    mysqlout=$?
    if [ $mysqlout -eq 1 ]; then
        printf "Please enter root password for MySQL.\n" 
        mysql -h $HOST -P $PORT --user=root --password < $1
        if [ $? -ne 0 ]; then
            printf "Error: Cannot execute $1\n"
            exit 4
        fi
    elif [ $mysqlout -eq 127 ]; then
        printf "Error: Cannot execute $1 - mysql command not found.\n"
        exit 5
    elif [ $mysqlout -ne 0 ]; then
        printf "Error: Cannot execute $1\n"
        exit 6
    fi
}

echo "Creating Database ehuser."
mysql -h ${HOST} -P ${PORT} --user=root --password=${PASSWORD} < ../db/app-database.sql > /dev/null 2>/dev/null
handle_error app-database.sql

#echo "Deploy platform schema"
#mysql -h ${HOST} -P ${PORT} --user=ehuser --password=ehuser ehuser < ../db/ehcore-platform-schema.sql
#if [ $? -ne 0 ]; then
#  printf "Error: Cannot execute platform-schema.sql\n"
#  exit 7
#fi

  flyway migrate -workingDirectory=../db-migration/base -configFiles=../flyway.conf
  flyway migrate -workingDirectory=../db-migration/db -configFiles=../flyway.conf

#echo "Deploy server schema"
#mysql -h $HOST -P $PORT --user=ehuser --password=ehuser ehuser < ../db/app-server-schema.sql
#if [ $? -ne 0 ]; then
#  printf "Error: Cannot execute app-server-schema.sql\n"
#  exit 7
#fi
#
#if [ -n "$BRANCH" ]; then
#    echo "Deploy branch schema"
#    if [ -f ../db/${BRANCH}-delta-schema.sql ]; then
#        mysql -h $HOST -P $PORT --user=ehuser --password=ehuser ehuser < ../db/${BRANCH}-delta-schema.sql
#        if [ $? -ne 0 ]; then
#          printf "Error: Cannot execute $BRANCH-delta-schema.sql\n"
#          exit 7
#        fi
#    fi
#
#    if [ -f ../db/${BRANCH}-delta-schema-02.sql ]; then
#        echo "Deploy branch 02 schema"
#        mysql -h $HOST -P $PORT --user=ehuser --password=ehuser ehuser < ../db/${BRANCH}-delta-schema-02.sql
#        if [ $? -ne 0 ]; then
#          printf "Error: Cannot execute $BRANCH-delta-schema-02.sql\n"
#          exit 7
#        fi
#    fi
#fi